/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.trick.admin.controller;

import it.trick.admin.App;
import it.trick.admin.Util;
import it.trick.admin.model.ChapterModel;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.web.WebView;

/**
 * FXML Controller class
 *
 * @author takahara
 */
public class EditChapterViewController extends AnchorPane implements Initializable {

    @FXML
    private TextArea contentsTextArea;
    @FXML
    private BorderPane editMainBorderPane;
    @FXML
    private TextArea descriptionTextArea;
    @FXML
    private TextArea keywordListTextArea;
    @FXML
    public HBox progressIndicatorHBox;
    @FXML
    private Label contentNameLabel;
    @FXML
    private WebView contentWebView;
    @FXML
    private ToggleGroup chapterToggleGroup;
    @FXML
    private SplitPane editView;
    private ChapterModel chapterModel;
    private EventHandler preservationEventHandler;

    /**
     * コンストラクタ
     */
    public EditChapterViewController(ChapterModel chapterModel) {
        this.chapterModel = chapterModel;
        init();
    }

    /**
     * コントロールの初期化
     */
    private void init() {

        // ---------------------------------------------------
        // FXMLのロードと設定
        // ---------------------------------------------------
        FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource("resource/fxml/edit_chapter_view.fxml"));
        fxmlLoader.setRoot(this);
        // 自分自身をコントロールとして設定
        fxmlLoader.setController(this);

        try {
            fxmlLoader.load();
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {

        // ToggleGroupの設定
        chapterToggleGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
            @Override
            public void changed(ObservableValue<? extends Toggle> ov,
                    Toggle toggle, Toggle new_toggle) {
                if (new_toggle != null) {
                    if (chapterToggleGroup.getSelectedToggle().getUserData().equals("view")) {
                        editView.setVisible(false);
                        contentWebView.setVisible(true);
                        setupWebView();
                    } else {
                        editView.setVisible(true);
                        contentWebView.setVisible(false);
                        setupEditView();
                    }
                }
            }
        });

        contentNameLabel.setText(chapterModel.getName() + "          (" + chapterModel.getKeyValueString() + ")");

        // webviewの初期化
        String urlString = App.getInstance().getSite()
                + "client/view/chapter?channel=" + ChannelTopController.getInstance().channelModel.getKeyValueString()
                + "&chapter=" + chapterModel.getKeyValueString();
        progressIndicatorHBox.visibleProperty().bind(contentWebView.getEngine().getLoadWorker().runningProperty());
        contentWebView.getEngine().load(urlString);

        // 保存イベントの設定
        preservationEventHandler = new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent t) {
                if (KeyCombination.keyCombination("Shortcut+S").match(t)) {
                    preservationAction();
                }
            }
        };
    }

    /**
     * webview の設定
     */
    private void setupWebView() {
        contentWebView.getEngine().reload();

        // 保存キーコンビネーションイベント
        editMainBorderPane.removeEventHandler(KeyEvent.KEY_RELEASED, preservationEventHandler);
    }

    /**
     * 編集ビューの設定
     */
    private void setupEditView() {
        // Description
        if (chapterModel.getDescription() == null) {
            chapterModel.setDescription("");
        }
        descriptionTextArea.setText(chapterModel.getDescription());

        // Content
        contentsTextArea.setText(chapterModel.getContent());

        // keyWord
        String keyWord = Util.keywordListToString(chapterModel.getKeyWordList());
        if (keyWord != null) {
            keywordListTextArea.setText(keyWord);
        } else {
            keywordListTextArea.setText("");
        }


        // 保存キーコンビネーションイベント
        editMainBorderPane.addEventHandler(KeyEvent.KEY_RELEASED, preservationEventHandler);

        // コンテキストメニューの設定
        setContextMenu();
    }

    /**
     * 保存アクション
     */
    private void preservationAction() {

        chapterModel.setDescription(descriptionTextArea.getText());

        chapterModel.setContent(contentsTextArea.getText());

        chapterModel.setKeyWordList(Util.keywordStringToList(keywordListTextArea.getText()));

        ChannelTopController.getInstance().updateChapterTask.setup(chapterModel);
        ChannelTopController.getInstance().updateChapterTask.restart();
    }

    /**
     * コンテキストメニューの設定
     */
    private void setContextMenu() {
        ContextMenu contextMenu = new ContextMenu();
        MenuItem H2TagMenuItem = new MenuItem("<h2>");
        MenuItem PTagMenuItem = new MenuItem("<p>");

        contextMenu.getItems().addAll(
                H2TagMenuItem,
                PTagMenuItem);

        H2TagMenuItem.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                String selectedText = contentsTextArea.getSelectedText();
                String tmp = contentsTextArea.getText();
                String newString = tmp.replaceAll(selectedText, "<h2>" + selectedText + "</h2>");
                contentsTextArea.setText(newString);
            }
        });

        PTagMenuItem.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                String selectedText = contentsTextArea.getSelectedText();
                String tmp = contentsTextArea.getText();
                String newString = tmp.replaceAll(selectedText, "<p>" + selectedText + "</p>");
                contentsTextArea.setText(newString);
            }
        });

        contentsTextArea.setContextMenu(contextMenu);
        contentsTextArea.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent t) {
                // コンテキストメニュー表示イベント
                if (t.isControlDown()) {
                    contentsTextArea.getContextMenu().show(contentsTextArea, t.getScreenX(), t.getScreenY());
                }
            }
        });
    }
}
